package wtws.util;

import java.nio.ByteBuffer;

public class ByteUtil {
	public static final byte[] EMPTY_1B = new byte[1];
	public static final byte[] EMPTY_2B = new byte[2];
	public static final byte[] EMPTY_4B = new byte[4];

	/**
	 * ASCII value
	 * 
	 * @param c
	 * @return
	 */
	public static byte[] toByte(char c) {
		byte arr[] = { (byte) c };
		return arr;
	}

	public static byte[] toByte(short i) {
		byte arr[] = { (byte) i };
		return arr;
	}

	public static byte[] toByte(int i) {
		byte arr[] = { (byte) i };
		return arr;
	}

	/**
	 * trim integer to 16 bit unsigned format
	 * 
	 * @param i
	 *            ,value range = 0 to 2^16-1
	 */
	public static byte[] to2Bytes(int i) {
		byte arr[] = new byte[2];
		ByteBuffer bb = ByteBuffer.allocate(4);
		bb.putInt(i);
		arr[0] = bb.get(2);
		arr[1] = bb.get(3);
		return arr;
	}

	public static byte[] to2Bytes(short i) {
		byte arr[] = new byte[2];
		ByteBuffer bb = ByteBuffer.allocate(2);
		bb.putShort(i);
		arr[0] = bb.get(0);
		arr[1] = bb.get(1);
		return arr;
	}

	/**
	 * long range = 0 to 2^32-1
	 * 
	 * @param i
	 */
	public static byte[] to4Bytes(long i) {
		byte arr[] = new byte[4];
		ByteBuffer bb = ByteBuffer.allocate(8);
		bb.putLong(i);
		arr[0] = bb.get(4);
		arr[1] = bb.get(5);
		arr[2] = bb.get(6);
		arr[3] = bb.get(7);
		return arr;
	}

	public static byte[] to4Bytes(int i) {
		byte arr[] = new byte[4];
		ByteBuffer bb = ByteBuffer.allocate(4);
		bb.putInt(i);
		arr = bb.array();
		return arr;
	}

	public static byte[] to4Bytes(double i) {
		byte arr[] = new byte[4];
		ByteBuffer bb = ByteBuffer.allocate(4);
		bb.putDouble(i);
		arr = bb.array();
		return arr;
	}

	final protected static char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	public static String bytesToHex(byte[] bytes) {
		char[] hexChars = new char[bytes.length * 2];
		int v;
		for (int j = 0; j < bytes.length; j++) {
			v = bytes[j] & 0xFF;
			hexChars[j * 2] = hexArray[v >>> 4];
			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
		}
		return new String(hexChars);
	}
}
